const tools = require("./tools.js")

const appKey = "4a2b69e74dea02ed696e7efcde6d3e8e"

module.exports = {
    get: function(url) {
        let body = tools.httpGet(url)
        if (body.status == '1')
            return body
        else {
            log('请求出错')
            log(url)
            log(body)
            let msg = "请求错误:"
            switch(body.infocode) {
                case '10005': msg += '请设置IP白名单'; break;
            }
        }
        
        return false
    },
    addressToGPS: function(address) {
        let url = "https://restapi.amap.com/v3/geocode/geo?key=" + appKey + "&city=guiyang&address=" + encodeURIComponent(address)
        let body = this.get(url)
        if (!body) return false
        // 这里需要进行容错
        return body.geocodes[0]["location"]
    },
    GPSToAddress: function(gps) {
        // gps = longitude + "," + latitude, 数字大的在前，数字小的在后
        let url = "https://restapi.amap.com/v3/geocode/regeo?key=" + appKey + "&location=" + gps
        let body = this.get(url)
        if(!body) return false
        return body.regeocode["formatted_address"]
    },
    requestPath: function (beginLocation, endLocation) {
        let url = "https://restapi.amap.com/v3/direction/driving?strategy=2&key=" + appKey + "&origin=" + beginLocation + "&destination=" + endLocation
        let body = this.get(url)
        log('路径信息')
        log(url)
        log(body)
        if(!body) return false

        let path = body.route.paths[0] // 因为一次可以获取多条路径
        
        let time = path["duration"]
        let distance = parseInt(path["distance"] / 1000)
        console.log("时间" + parseInt(time / 60) + "分钟" + "==>" + "距离:" + distance) 
        
        return { distance: distance, time: parseInt(time / 60) }
    },
    getPathInfo: function(addressBegin, addressEnd, myLocation) {

        let endLocation = this.addressToGPS(addressEnd)
        if(!endLocation) {
            return "终点地址转换失败"
        }

        let beginLocation = this.addressToGPS(addressBegin)
        if(!beginLocation) {
            return "起点地址转换失败"
        }
        
        console.log("起点坐标:" + beginLocation)
        console.log("终点坐标:" + endLocation)

        let pathInfo = api.requestPath(beginLocation, endLocation)
        if(!pathInfo) {
            return "路径请求错误"
        }

        return pathInfo
    }
}
